# app/controllers/family/pet.py
from typing import List, Optional, Tuple
from app.utils.request import RequestHandler
from app.core.crud import CRUDBase
from app.models.family.pet import Pet
from app.schemas.family.pet import PetCreate, PetUpdate
from app.services.family.pet import pet_service
from app.schemas.base.error_code import *
from app.core.exceptions import BusinessError
from app.utils.app_log import logger
from tortoise.expressions import Q

class PetController():
    async def pet_list(self, page: int, page_size: int, q: Q) -> Tuple[int, List[dict]]:
        """获取宠物列表"""
        try:
            total, pet_objs = await pet_service.list(page=page, page_size=page_size, search=q)
            data = [await obj.to_dict() for obj in pet_objs]
            # logger.info(f"获取宠物列表成功，共有{total}条数据 {pet_objs} {data}")
            return total, data
        except Exception as e:
            raise BusinessError(RESOURCE_ACCESS_DENIED, details=f"获取宠物列表出错：{str(e)}")

    async def get_pet_info(self, pet_id: int,family_id: int) -> dict:
        """获取宠物详情"""
        try:
            
            pet_obj = await pet_service.get_pet_by_family(pet_id,family_id)
            if not pet_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="宠物"), details="宠物不存在")
            pet_dict = await pet_obj.to_dict()
            return pet_dict
        except Exception as e:
            raise BusinessError(RESOURCE_NOT_FOUND.format(resource="宠物"), details=f"宠物不存在：{str(e)}")

    async def remove_pet(self, pet_id: int,family_id:int =None) -> bool:
        """删除宠物"""
        try:
            
            pet_obj = await pet_service.get_pet_by_family(pet_id,family_id)
            if not pet_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="宠物"), details="宠物不存在")
            await pet_service.remove(pet_id)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_DELETE_FAILED.format(resource="宠物"), details=f"删除宠物失败 {str(e)}")

    async def create_pet(self, pet_in: PetCreate) -> Pet:
        """创建宠物"""
        try:
            # 检查同名宠物是否已存在
            existing_pet = await pet_service.model.filter(
                name=pet_in.name, 
                family_id=pet_in.family_id,
                is_deleted=False
            ).first()
            if existing_pet:
                raise BusinessError(RESOURCE_ALREADY_EXISTS.format(resource="宠物"), details="该宠物名称已存在")
            
            new_pet = await pet_service.create(pet_in)
            return new_pet
        except Exception as e:
            raise BusinessError(RESOURCE_CREATE_FAILED.format(resource="宠物"), details=f"创建宠物失败 {str(e)}")

    async def update_pet_info(self, pet_id: int, obj_in: PetUpdate,family_id:int = None) -> bool:
        """更新宠物信息"""
        try:
            
            pet_obj = await pet_service.get_pet_by_family(pet_id,family_id)
            if not pet_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="宠物"), details="宠物不存在")
            await pet_service.update(pet_id, obj_in)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_UPDATE_FAILED.format(resource="宠物"), details=f"更新宠物失败 {str(e)}")

pet_controller = PetController()